#include "RIVIAImage.h"
#include <QImage>
#include "RIVIALayer.h"

using namespace cv;

RIVIAImage::RIVIAImage(const cv::Mat &Mat):
    m_nCurLayerID(0),
    m_nMaxLayerID(1),   //LayerID start from 1
    m_pLayersHash(nullptr)
{
    m_pLayersHash = new QHash<int, RIVIALayer*>;
    newLayer(Mat);
}

RIVIAImage::~RIVIAImage()
{
    QHash<int, RIVIALayer*>::iterator Iter;
    for(Iter = m_pLayersHash->begin(); Iter != m_pLayersHash->end(); ++Iter)
    {
        delete Iter.value();
    }
    delete m_pLayersHash;
    m_pLayersHash = nullptr;
}

QImage RIVIAImage::getDisplayQImage()
{
    genAllMats();
    return QImage((const uchar*)(m_AllMats.data), m_AllMats.cols, m_AllMats.rows, QImage::Format_RGB888).rgbSwapped();
}

Mat RIVIAImage::getAllMats()
{
    genAllMats();
    return m_AllMats;
}

RIVIALayer *RIVIAImage::newLayer(const cv::Mat &Mat)
{
    int nLayerID = m_nMaxLayerID++;
    RIVIALayer* pLayer = new RIVIALayer(Mat);
    m_pLayersHash->insert(nLayerID, pLayer);
    setCurLayerID(nLayerID);
    return pLayer;
}

RIVIALayer *RIVIAImage::getCurLayer()
{
    RIVIALayer* pLayer = nullptr;
    QHash<int, RIVIALayer*>::iterator Iter = m_pLayersHash->find(m_nCurLayerID);
    if(Iter != m_pLayersHash->end())
        pLayer = Iter.value();
    return pLayer;
}

void RIVIAImage::deleteCurLayer()
{
    QHash<int, RIVIALayer*>::iterator Iter = m_pLayersHash->find(m_nCurLayerID);
    if(Iter != m_pLayersHash->end())
    {
        RIVIALayer* pLayer = Iter.value();
        delete pLayer;
        m_pLayersHash->remove(m_nCurLayerID);
    }
}

void RIVIAImage::setCurLayerID(int nLayerID)
{
    m_nCurLayerID = nLayerID;
}

void RIVIAImage::genAllMats()
{
    Mat matproc = m_pLayersHash->begin().value()->getMatProc(); //first layer mat
    matproc.copyTo(m_AllMats);
}
